﻿
$(function () {
    _vmBase = new viewModel();

    _vmBase.init();
})

function viewModel() {
    var me = this;
    VueViewModelBase.call(me);
    viewModelExtend.call(me);

    
    me.tableListUrl = _getTableListUrl;
    me.addUrl = _updateModelUrl;
    me.delUrl = _deleteModelUrl;
    me.tabObj = $('#tb_roles');

    me.loadedResource;

    //重写方法
    me.init = function () {
        

        me.initTableList();

        //添加监听对象
        me.addMonitor();


        //me.initRoleAuthoritySplitter();
       
    }

    me.initTableList = function () {
        var options = {
            search: false,
            singleSelect:true,
            columns: [
                {
                    checkbox: true
                },
                {
                    field: 'name',
                    title: '角色名称'
                    
                },
                {
                    field: 'status',
                    title: '状态',
                    filterControl: "select",
                    filterData: "var:_isEnabledSelect",
                    formatter: function (value, row, index) {
                        var enabledLabel = '<span class="label label-success">' + _enabledStr + '</span>';
                        var disabledLabel = '<span class="label label-default">' + _disabledStr + '</span>';
                        if (row.status) {
                            return enabledLabel;
                        } else{
                            return disabledLabel;
                        }
                    }
                },
                {
                    field: 'id',
                    title: '操作',
                    formatter: function (value, row, index) {
                        

                        var enabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onEnabledClick(this,' + index + ',\'' + row.id + '\',\'' + _enabledRoleUrl + '\',\'' + _disabledRoleUrl + '\',event)"><i class="fa fa-play-circle"></i>' + _enabledStr + '</a>';
                        var disabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onDisabledClick(this,' + index + ',\'' + row.id + '\',\'' + _enabledRoleUrl + '\',\'' + _disabledRoleUrl + '\',event)"><i class="fa fa-stop-circle"></i>' + _disabledStr + '</a>';

                        if (row.status) {
                            return disabledEle;
                        } else if (!row.status) {
                            return enabledEle;
                        }

                    }
                }
            ],
            filterControl: true,
            queryParams: function (params) {
                var filter = "";
                if (params.filter != undefined && params.filter != null) {
                    filter = params.filter;
                }
                
                var temp = {
                    rows: params.limit,                         //页面大小
                    page: (params.offset / params.limit) + 1,   //页码
                    queryKey: vueModel.queryKey,
                    treeId: vueModel.treeId,
                    filter: filter
                };
                return temp;
            }
        }
        me.initList(options);

    }


    me.setSelectedData = function () {
        var selectRows = me.tabObj.bootstrapTable('getSelections');
        me.selections = selectRows;

        if (selectRows.length <= 0) {
            vueModel.selectedData = false;
        } else {
            //判断点击的当前行数据是否有效
            var lastSelectObj = selectRows[selectRows.length - 1];
            if (!lastSelectObj.status) {
                vueModel.selectedData = false;
            } else {
                vueModel.selectedData = true;
            }

            
        }
    }

    /*
     * obj 当前操作html对象
     * id  行绑定对象Id
     * opEnableUrl 启用功能url
     * opDisAbleUrl 禁用功能Url
     */
    me.onEnabledClick = function (obj,index, id, opEnableUrl, opDisAbleUrl, e) {
        e.stopPropagation();//行内编辑事件，禁止事件传递（不触发bootstrap table 的clickrow事件）
        $dh.post(opEnableUrl, { id: id }, function (result) {
            if (result.Status == ResultStatus.OK) {
                //刷新
                //vueModel.search();
                $dh.msg("启用成功");

                var disabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onDisabledClick(this,\'' + id + '\',\'' + opEnableUrl + '\',\'' + opDisAbleUrl + '\',event)"><i class="fa fa-stop-circle"></i>' + _disabledStr + '</a>';
                var parentObj = $(obj).parent();
                //parentObj.html("");
                parentObj.html(disabledEle);

                var enabledLabel = '<span class="label label-success" id="' + id + '">' + _enabledStr + '</span>';
                var parentSb = parentObj.prev();
                parentSb.html(enabledLabel);

                //更新当前行数据
                me.tabObj.bootstrapTable('updateRow', {
                    index: index,
                    row: {
                        status: true
                    }
                }); 
            }

        });

    }

    /*
    * obj 当前操作html对象
    * id  行绑定对象Id
    * opEnableUrl 启用功能url
    * opDisAbleUrl 禁用功能Url
    */
    me.onDisabledClick = function (obj,index, id, opEnableUrl, opDisAbleUrl, e) {
        e.stopPropagation(); //行内编辑事件，禁止事件传递（不触发bootstrap table 的clickrow事件）
        $dh.post(opDisAbleUrl, { id: id }, function (result) {
            if (result.Status == ResultStatus.OK) {
                //刷新
                //vueModel.search();
                $dh.msg("禁用成功");

                var enabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onEnabledClick(this,\'' + id + '\',\'' + opEnableUrl + '\',\'' + opDisAbleUrl + '\',event)"><i class="fa fa-play-circle"></i>' + _enabledStr + '</a>';
                var parentObj = $(obj).parent();
                parentObj.html(enabledEle);

                var disabledLabel = '<span class="label label-default" id="' + id + '">' + _disabledStr + '</span>';
                var parentSb = parentObj.prev();
                parentSb.html(disabledLabel);

                //更新当前行数据
                me.tabObj.bootstrapTable('updateRow', {
                    index: index,
                    row: {
                        status: false
                    }
                }); 

            }

        });
    }


 

}

function viewModelExtend() {
    var me = this;

    me.addMonitor = function (monitorObj) {
        var targetObj = vueModel.entityObj;

        if (monitorObj != null && monitorObj != undefined) {
            me.addMonitorObj(targetObj, monitorObj);
        } else {
            var addObj = {
                Id:'',
                Name: '',
                Status: true
            };
            me.addMonitorObj(targetObj, addObj);
        }
    }

    //角色权限分配
    me.roleAuthorityAssign = function () {

        _layerIndex = layer.open({
            type: 1,
            title: "角色资源", //不显示标题
            area: ['900px', '600px'], //宽高
            content: $('#roleAuthorityDiv'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确认提交', '关闭'],
            yes: function () {
                $dh.msg("提交");
                layer.close(_layerIndex);
            },
            no: function () {
                $dh.msg("关闭");
                layer.close(_layerIndex);
            },
            success: function (layero, index) {
                //加载资源
                me.loadResources();
            }
        });

    }

    //为当前角色加载资源
    me.loadResources = function () {

        if (me.loadedResource != null && me.loadedResource != undefined) {
            me.loadedResource.bootstrapTable('destroy');
        }

        var roleAuthority=$('#tb_roleAuthority').bootstrapTable({
            url: _getRoleResourcesUrl,
            method: 'get',                      //请求方式（*）
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            toolbar: '#resourceToolBar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            //singleSelect: true,
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "Id",                     //每一行的唯一标识，一般为主键列
            detailView:true,                    //显示子表
            columns: [{
                checkbox: true

            }, {
                field: 'name',
                title: '名称',
                filterControl: "input"
            }

            ],
            //注册加载子表的事件。注意下这里的三个参数！
            onExpandRow: function (index, row, $detail) {
                _vmBase.initButtonForResource(index, row, $detail);
            },
            onClickRow: function (row, $element) {
                
            },
            onCheck: function (row) {
                
            }

        });
        me.loadedResource = roleAuthority;

    }

    //为资源加载按钮
    me.initButtonForResource = function (index, row, $detail) {
        var parentid = row.id;
        var cur_table = $detail.html('<table></table>').find('table');

        //加载按钮功能集

        me.loadButtonFuncs(parentid,function (result) {
            //加载按钮列表
            me.loadButtons(cur_table, result);
        });


        
       
    }

    me.loadButtonFuncs = function (resourceId, callback) {

        $dh.get(_getFuncsUrl, { resourceId: resourceId}, function (result) {

            //获取功能后，生成下来数据

            var seles = "<select> ";
            seles += '<option value=""></option>';
            for (var i = 0; i < result.length; i++) {
                var op = '<option value ="' + result[i].id + '">' + result[i].description + '</option>';
                seles += op;
            }
            seles += "</select>";

            callback(seles);
        });

    }
    //按钮列表
    me.loadButtons = function (childTabObj, selectElements) {

        var resourceButtonTab = $(childTabObj).bootstrapTable({
            url: _getButtonsUrl,
            method: 'get',                      //请求方式（*）
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            //toolbar: '',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "Id",                     //每一行的唯一标识，一般为主键列
            detailView: false,                    //显示子表
            columns: [{
                checkbox: true

            }, {
                field: 'name',
                title: '按钮名称',
                filterControl: "input"
            },
            {
                field: 'icon',
                title: '图标',
                formatter: function (value, row, index) {
                    return '<i class="' + row.icon + '"></i>';
                }
            }, {

                filed: 'funcId',
                title: '功能',
                formatter: function (value, row, index) {
                    return selectElements;
                }
            }

            ],
            //onClickRow: function (row, $element) {
            //    var res = 1;
            //},
            //onCheck: function (row) {
            //    var res = 2;
            //},
            //onUncheck: function (row) {
            //    var res = 5;

            //},
            onCheckAll: function (rows) {
                //$(cur_table).bootstrapTable('checkAll');
                //var currentChectBox = $(resourceButtonTab[0]).find('thead').find('tr').find('th').find('input');
                //currentChectBox.attr("checked", true);


            },
            onUncheckAll: function (rows) {


            },
            onLoadSuccess: function (data) {
                //按钮列表加载完毕,加载有权限按钮

            }

        });

        return resourceButtonTab;
    }

    //初始化 splitter
    //用childDetailView代替
    me.initRoleAuthoritySplitter = function () {
        $('#roleAuthorityMainSplitter').jqxSplitter({ width: 800, height: 480, panels: [{ size: 300 }] });
    }
    
}


